define((['jquery', 'pAjax']), () => {
    function List() {
        let ul = document.querySelector('#ul')
        // console.log(ul)
        let span=document.querySelector('.count>span')
        // console.log(span)
        pAjax({ url: '/libs/goodsList.json' })
            .then(res => {
                // console.log(res)
                let data = JSON.parse(res)
                // console.log(data)
                data = data.slice(0, 10)
                // console.log(data)
                render()
                function render(){
                data.forEach(item => {
                    ul.innerHTML += `
                        <li data-id=${item.product_id}><a href="./details.html?id=${item.product_id}";">
                            <div class="a">
                            <img src="${item.images[0]}">
                            <p class="title hide">${item.title}</p>
                            <p class="price">${item.price_min + '元'}</p>
                            </a>
                            <button data-id=${item.product_id}>加入购物车</button>
                            </div>
                        </li> 
                        
                    `

                })
                bindHtml()
            }
            function bindHtml(){
                ul.onclick=(e)=>{
                    let target=e.target||e.srcElement
                    if(target.nodeName=='BUTTON'){
                        let id=target.dataset.id - 0
                        // console.log(id)
                        // console.log(data)
                        let goods = data.find(item=>{return item.product_id == id})
                        console.log(goods)
                        // console.log(list)
                        let list = JSON.parse(localStorage.getItem('cart')) || []
                        // console.log(list)
                        if(!list.length){
                            list.push(goods)
                            goods.cart_num=1
                        }
                        else{
                            let res=list.some(item=>{return item.product_id==id})
                            // console.log(res)
                            if(res){
                                let index=list.findIndex(item=>{return item.product_id==id})
                                list[index].cart_num++
                            }else{
                                list.push(goods)
                                goods.cart_num=1
                            }
                            
                        }
                        localStorage.setItem('cart',JSON.stringify(list))
                    }
                }
            }
            })
        
    }
    return {
        List: List
    }
})